package utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import models.Student;
import models.Students;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class EditToXml {

    public EditToXml() {
    }

    public void deleteStudentToXml(String path, int[] id) throws IOException {
        //List<Student> students = new ArrayList<Student>();
        Student student = new Student();
        int k;
        try { 
//            File file = new File(path);
//            JAXBContext context = JAXBContext.newInstance(Students.class);
//            Unmarshaller jaxbUnmashaller = context.createUnmarshaller();
            LoadXml loadXml = new LoadXml(path);
            Students students = loadXml.getStudents();
            
            List<Student> tempStu = new ArrayList<Student>();
            for (int j = 0; j < id.length; j++) {
                for (Student i : students.getListStudent()) {
                    if (i.getId() == id[j]) {
                        tempStu.add(i);
                    }
                }
            }
            if (id.length > 0) {
                for (int i = 0; i < id.length; i++) {
                    //k =id[i];
                    students.getListStudent().remove(tempStu.get(i));
                }
            }

            // viet ra file
            BufferedWriter writer = null;
            writer = new BufferedWriter(new FileWriter(new File(path)));
            JAXBContext context = JAXBContext.newInstance(Students.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(students, writer);
            writer.close();

        } catch (JAXBException ex) {
            ex.printStackTrace();
        }

    }

    public void editStudentToXml(String path, Student student) {
        try {
            Students students = new Students();
            LoadXml loadXml = new LoadXml(path);
            List<Student> studentList = new ArrayList<>();
            studentList = loadXml.getStudents().getListStudent();

            for (Student tempStudent : studentList) {
                if (tempStudent.getId() == student.getId()) {
                    studentList.remove(tempStudent);
                    studentList.add(student);
                    break;
                }
            }

            students.setListStudent(studentList);
            //
            BufferedWriter writer = null;
            writer = new BufferedWriter(new FileWriter(new File(path)));

            JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(students, writer);
            //writer.close();
        } catch (IOException ex) {
            Logger.getLogger(AddToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void deleteObjectToXml(String path, int[] indexValue) {
        try {
            String filepath = path;
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);
            doc.getDocumentElement().normalize();
            //Delete
            Node students = doc.getElementsByTagName("students").item(0);

            Node student = doc.getElementsByTagName("student").item(indexValue[0] - 1);
            students.removeChild(student);
            if (indexValue.length > 1) {
                for (int j = 0; j < indexValue.length - 1; j++) {
                    Node student2 = doc.getElementsByTagName("student").item(indexValue[j] - 1 - j);
                    students.removeChild(student2);
                    System.out.println("");
                }
            }

            doc.getDocumentElement().normalize();
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);

            System.out.println("Done");
            //is Delete


        } catch (ParserConfigurationException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void editObjectToXml(String path, Student objStudent, int indexValue) {
        try {
            String filepath = path;
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);
            doc.getDocumentElement().normalize();
            //is Edit

            Node student = doc.getElementsByTagName("student").item(indexValue - 1);

            NodeList list = student.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {

                Node node = list.item(i);
                // update
                if ("firstname".equals(node.getNodeName())) {
                    //node.getFirstChild().setTextContent(objStudent.getFirstName());
                    node.setTextContent(objStudent.getFirstName());
                }
                if ("lastname".equals(node.getNodeName())) {
                    node.setTextContent(objStudent.getLastName());
                }
                if ("address".equals(node.getNodeName())) {
                    node.setTextContent(objStudent.getAddress());
                }
                if ("age".equals(node.getNodeName())) {
                    node.setTextContent(objStudent.getAge() + "");
                }
                if ("dob".equals(node.getNodeName())) {
                    node.setTextContent(objStudent.getDob());
                }
                if ("note".equals(node.getNodeName())) {
                    node.setTextContent(objStudent.getNote());
                }
            }
            doc.getDocumentElement().normalize();
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);

            System.out.println("Done");
            //is Delete


        } catch (ParserConfigurationException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(EditToXml.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}